# 确保脚本目录存在
New-Item -ItemType Directory -Force -Path scripts

# 创建 SQL 脚本
$sqlScript = @"
-- 创建数据库
CREATE DATABASE IF NOT EXISTS dynamic_db;

-- 创建用户并授权
CREATE USER IF NOT EXISTS 'dynamic_user'@'localhost' IDENTIFIED BY 'dynamic_password';
CREATE USER IF NOT EXISTS 'dynamic_user'@'%' IDENTIFIED BY 'dynamic_password';

-- 授予权限
GRANT ALL PRIVILEGES ON dynamic_db.* TO 'dynamic_user'@'localhost';
GRANT ALL PRIVILEGES ON dynamic_db.* TO 'dynamic_user'@'%';

-- 刷新权限
FLUSH PRIVILEGES;
"@

Set-Content -Path "scripts\init-mysql.sql" -Value $sqlScript

# 提示用户输入 MySQL root 密码
$mysqlRootPassword = Read-Host "Please enter MySQL root password" -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($mysqlRootPassword)
$plainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

# 执行 SQL 脚本
try {
    mysql -u root -p"$plainPassword" < scripts\init-mysql.sql
    Write-Host "MySQL user 'dynamic_user' and database 'dynamic_db' created successfully."
} catch {
    Write-Host "Failed to create MySQL user and database: $_"
    exit 1
}

# 更新 .env 文件
$envContent = @"
# 数据库类型: postgres 或 mysql
DB_TYPE=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=dynamic_user
DB_PASSWORD=dynamic_password
DB_NAME=dynamic_db
"@

Set-Content -Path ".env" -Value $envContent
Write-Host ".env file updated with MySQL configuration." 